//
//  BRScrollAdView.swift
//  ADVIEW
//
//  Created by Burn on 2019/1/8.
//  Copyright © 2019 nmgxysh. All rights reserved.
//

import UIKit

@objc protocol BRScrollAdViewDelegate : NSObjectProtocol{
    func adPicViewDidSelectedPicModel(pictrueModel : BRScrollAdViewProtocol)
    func adPicViewClickPicModel(pictrueModel : BRScrollAdViewProtocol)
}


public class BRScrollAdView: UIView {
    //  delegate
    weak var delegate : BRScrollAdViewDelegate?
    //  加载图片block
    fileprivate var loadImageBlock : ((_ imageView : UIImageView,_ imageURL : URL) -> ())?
    //  保存模型数组
    fileprivate var picModels : Array<AnyObject> = Array()
    //  翻倍添加无限循环
    let radio : Int = 10
    //  相框数组
    fileprivate var adPictures : [UIImageView] = [UIImageView]()
    //  当前下表
    var currentPage : Int = 0
    
    //  ScrollView
    fileprivate lazy var contentView : UIScrollView = {
        let contentView : UIScrollView = UIScrollView()
        contentView.isPagingEnabled = true
        contentView.delegate = self
        contentView.showsHorizontalScrollIndicator = false
        return contentView
    }()
    
    //  Timer
    fileprivate lazy var scrollTimer : Timer! = {
        let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        //        RunLoop.current.add(timer, forMode: .commonModes)
        return timer
    }()
    
    //  pageControl
    fileprivate lazy var pageControl : UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = UIColor.gray
        pageControl.currentPageIndicatorTintColor = UIColor.orange
        pageControl.hidesForSinglePage = true
        return pageControl
    }()
    
    public init(frame: CGRect,title : String) {
        super.init(frame: frame)
    }
    
    //  初始化方法
    public init(frame: CGRect,loadImage : @escaping (_ imageView : UIImageView,_ imageURL : URL) -> ()) {
        super.init(frame: frame)
        
        loadImageBlock = loadImage
        self.addSubview(contentView)
        self.addSubview(pageControl)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        scrollTimer.invalidate()
        scrollTimer = nil
    }
}

extension BRScrollAdView{
    
    @objc func timerAction(){
        let page = currentPage + 1
        contentView.setContentOffset(CGPoint(x: contentView.frame.size.width * CGFloat(page), y: 0), animated: true)
    }
    
    public func setPicModels(picModels : Array<AnyObject>){
        //  保存models
        self.picModels = picModels
        
        //  移除之前的控件
        for imagView in adPictures { imagView.removeFromSuperview()  }
        adPictures.removeAll()
        
        //  根据模型添加新的控件
        let baseCount = picModels.count
        var count = baseCount
        if baseCount > 1{
            count = baseCount * radio   //  baseCount * 10 正好是 三倍 比如 源 Image1 Image2 Image3 的话 * 10 之后是三组 每一组中有 Image1 Image2 Image3
        }
        for i in 0..<count{
            let pic : BRScrollAdViewProtocol = picModels[i % baseCount] as! BRScrollAdViewProtocol
            
            let imageView = UIImageView()
            imageView.tag = adPictures.count
            
            //  回调设置图片
            if (loadImageBlock != nil)  {
                self.loadImageBlock!(imageView,pic.adImageURL!)
            }
            //  添加手势
            let gesTap = UITapGestureRecognizer(target: self, action: #selector(jumpToLink(ges:)))
            imageView.isUserInteractionEnabled = true
            imageView.addGestureRecognizer(gesTap)
            
            contentView.addSubview(imageView)
            //  数组中添加ImageView
            adPictures.append(imageView)
        }
        //  设置pageControl 的页数
        pageControl.numberOfPages = picModels.count
        
        //  布局
        self.setNeedsLayout()
        
        //  根据条件激活Timer
        if picModels.count > 1{
            scrollTimer.fire()
        }else{
            scrollTimer.invalidate()
            scrollTimer = nil
        }
    }
    //  ImageViewClick
    @objc func jumpToLink(ges : UITapGestureRecognizer){
        
        //  获取imageView
        let imageView = ges.view
        //  获取具体下表
        let tag = imageView!.tag % picModels.count
        //  获取Model
        let adModel = picModels[tag] as! BRScrollAdViewProtocol
        //
//        guard (adModel.clickBlock) != nil else { return }
        
        //        adModel.clickBlock!()
        delegate?.adPicViewClickPicModel(pictrueModel: adModel)
        
    }
    override public func layoutSubviews() {
        super.layoutSubviews()
        
        contentView.frame = bounds
        pageControl.frame = CGRect(x: 0, y: frame.size.height - 20, width: frame.width, height: 20)
        
        let width = bounds.size.width
        let heigth = bounds.size.height
        let count = adPictures.count
        for i in 0..<count{
            adPictures[i].frame = CGRect(x: CGFloat(i) * width, y: 0, width: width, height: heigth)
        }
        contentView.contentSize = CGSize(width: CGFloat(adPictures.count) * width, height: 0)
        scrollViewDidEndDecelerating(contentView)
    }
}

extension BRScrollAdView{
    fileprivate func caculateCurrnetPage(scrollView : UIScrollView){
        if picModels.count == 0{
            return
        }
        if picModels.count == 1{
            currentPage = 1
            delegate?.adPicViewDidSelectedPicModel(pictrueModel: picModels[pageControl.currentPage] as! BRScrollAdViewProtocol)
            return
        }
        
        let min = picModels.count * (radio / 2)
        let max = picModels.count * (radio / 2 + 1)
        //  获取下标
        var page : Int = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = page % picModels.count
        
        if page < min || page > max{
            page = min + page % picModels.count
            //                        scrollView.setContentOffset(CGPoint(x: page * Int(scrollView.frame.size.width), y: 0), animated: false)
            scrollView.contentOffset = CGPoint(x: page * Int(scrollView.frame.size.width), y: 0)
        }
        currentPage = page
        delegate?.adPicViewDidSelectedPicModel(pictrueModel: picModels[pageControl.currentPage] as! BRScrollAdViewProtocol)
    }
    fileprivate func setupTimer(){
        scrollTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        RunLoop.current.add(scrollTimer, forMode: .commonModes)
    }
}

extension BRScrollAdView : UIScrollViewDelegate{
    
    public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        guard scrollTimer != nil else { return }
        scrollTimer.invalidate()
        scrollTimer = nil
    }
    
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if adPictures.count > 1{
            setupTimer()
        }
    }
    //2
    public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        caculateCurrnetPage(scrollView: scrollView)
    }
    //1
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        caculateCurrnetPage(scrollView: scrollView)
        
    }
}
